package cn.kooki.app.duobao.util;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemClock;
import android.support.v7.app.AlertDialog;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;

import cn.kooki.app.duobao.base.BaseActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.base.CheckResponse;
import cn.kooki.app.duobao.data.constant.Constants;
import retrofit.RetrofitError;

/**
 * Created by xiong on 2016/1/26.
 */
public class UpdateUtils {

    private BaseActivity activity;

    private static UpdateUtils instance;

    public static UpdateUtils getinstance() {
        if (instance == null) {
            instance = new UpdateUtils();
        }
        return instance;
    }
    private boolean isShowTips = true;

    public void setShowTips(boolean showTips) {
        isShowTips = showTips;
    }

    public void update(BaseActivity activity) {
        this.activity = activity;
        checkNewVersion();
    }

    public void install(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        activity.startActivity(intent);
    }


    private String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
    }


    private void checkNewVersion() {

        MainFactory.getApiInstance().checkVersion(new retrofit.Callback<CheckResponse>() {
            @Override
            public void success(CheckResponse baseResponse, retrofit.client.Response response) {
                if (baseResponse.data != null) {
                    int code = PackageUtils.getAppVersionCode(activity);
                    if (baseResponse.data.versionCode > code) {
                        showVersionDialog(baseResponse.data);
                    } else {
                        if (isShowTips) {
                            activity.showToastMessage("当前已是最新版本");
                        }
                    }
                } else {
                    if (isShowTips) {
                        activity.showToastMessage("当前已是最新版本");
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                if (isShowTips) {
                    activity.showToastMessage("当前已是最新版本");
                }
            }
        });

    }

    private void showVersionDialog(final CheckResponse.VersionItem data) {
        new AlertDialog.Builder(activity).setTitle("有新的版本:" + data.versionName)
                .setMessage(data.msg)
                .setPositiveButton("取消", null)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showdownloading(data.url);
                    }
                }).show();
    }


    private void showdownloading(String url) {
//        createProgressDialog("新版本", "修复BUG");
        download(Constants.APP_DOWNLOAD_PATH.toString(), url);
    }


    private void download(final String destFileDir, final String url) {
        FileDownloader.getImpl().create(url).setPath(destFileDir + SystemClock.currentThreadTimeMillis() + getFileName(url)).setListener(new FileDownloadListener() {

            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                activity.createProgressDialog("下载中", null);
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                activity.updateProgressDialog(totalBytes, soFarBytes);
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {

            }

            @Override
            protected void completed(BaseDownloadTask task) {
                activity.dismissDialog();
                String path = task.getPath();
                install(new File(path));
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {

            }

            @Override
            protected void warn(BaseDownloadTask task) {

            }
        }).start();


    }
}
